import {getTodayDate, stringToDate} from "../tools";
import {EcpmModel} from "../models/ecpmModel";
import logger from "../logger";
import axios from "axios";
import {config} from "../config/config";
import {Get_ecpm} from "../types/clientType";
import {getNewToken, getToken} from "./tokenService";
import {GamesModel} from "../models/gamesModel";
import exp from "node:constants";

require('express-async-errors');

export const handlerEcpm = async (data: any) => {
    try {

        const token_data: any = await getToken(data.appid, data.secret);
        let result = await getEcpm({
            open_id: data.openid,
            mp_id: data.appid,
            access_token: token_data.access_token,
            date_hour: getTodayDate(),
            page_no: 1,
            page_size: 500
        });
        if (result.data.err_no == '28001003') {
            const new_token_data: any = await getNewToken(data.appid, data.secret);
            result = await getEcpm({
                open_id: data.openid,
                mp_id: data.appid,
                access_token: new_token_data.access_token,
                date_hour: getTodayDate(),
                page_no: 1,
                page_size: 500
            });
        }
        if (result.data.err_no === 0 && result.data.err_msg === '' && result.data.data.total > 0) {
            ecpm_save_list(result.data.data.records, data.appid).then();
        }
    } catch (err) {
        logger.error({msg: '获取ecpm错误:', err});
    }
}

export async function ecpm_save_list(data: any, appid: any) {
    try {
        const bulkOps = data.map((record: any) => ({
            updateOne: {
                filter: {id: record.id},
                update: {
                    $set: {
                        cost: record.cost,
                        event_name: record.event_name,
                        event_time: stringToDate(record.event_time).getTime(),
                        open_id: record.open_id,
                        id: record.id,
                        appid: appid
                    }
                },
                upsert: true
            }
        }));
        return await EcpmModel.bulkWrite(bulkOps);
    } catch (error) {
        logger.error({msg: '存储ecpm错误', error: error});
    }
}

export async function getEcpm(data: Get_ecpm) {
    return await axios.get(config.get_ecpm, {
        params: data
    });
}

export const handler_update = async (appid: string, date: string) => {
    let game_data: any = await GamesModel.find({appid: appid});
    let page_no: number = 1;
    let page_size: number = 500;
    while (true) {
        let {
            records,
            total,
            err_no
        } = await fetchRecords(appid, '', date, game_data[0].token.access_token, page_no, page_size);
        if (err_no === 28001003) {
            await getNewToken(appid, game_data[0].secret);
            game_data = await GamesModel.find({appid: appid});
            const data = await fetchRecords(appid, '', date, game_data[0].token.access_token, page_no, page_size);
            records = data.records;
            total = data.total;
            err_no = data.err_no
        }
        if (err_no !== 0) {
            logger.error(`更新 ecpm 错误: ${err_no}`);
            break;
        }
        await ecpm_save_list(records, appid);

        if (records.length < page_size) {
            break;
        }

        page_no++;
        await new Promise(resolve => setTimeout(resolve, 200));
    }
    logger.info(' 更新完成 ');
}

async function fetchRecords(mp_id: string, open_id: string, date_hour: string, access_token: string, page_no: number, page_size: number) {
    try {
        const response = await axios.get(config.get_ecpm, {
            params: {
                mp_id,
                open_id,
                date_hour,
                access_token,
                page_no,
                page_size
            }
        });
        const {records, total} = response.data.data;
        const err_no = response.data.err_no;
        return {records, total, err_no};
    } catch (error) {
        console.error('请求失败:', error);
        return {records: [], total: 0, err_no: -1};
    }
}

